<?php

namespace app\admin\controller;

use app\admin\controller\Base;
use app\common\model\Coupon;
use app\common\model\UserVip;
use \think\Request;
use think\facade\View;
use app\common\model\User as UserModel;
use app\common\model\ProfitMoney;
use app\common\model\ProfitMoney2;
use app\common\model\ProfitIntegral;
use app\common\model\Shang;
use app\common\model\GoodsList;
use app\common\model\Goods;
use app\common\model\ClimbRank;

use app\common\model\Order;
use app\common\model\OrderList;
use app\common\model\UserAccount;
use app\common\model\UserLoginIp;
use think\facade\Db;

class User extends Base
{
    /**
     * 用户列表
     */
    public function index()
    {
        $user_id = trim(input('get.user_id'));
        $mobile = trim(input('get.mobile'));
        $nickname = trim(input('get.nickname'));
        $addtime = trim(input('get.addtime'));
        $last_login_ip = trim(input('get.last_login_ip'));
        $last_login_ip2 = $last_login_ip;
        $whe = [];
        if ($user_id) {
            $whe[] = ['id', '=', $user_id];
        }
        if ($nickname) {
            $whe[] = ['nickname', 'like', '%' . $nickname . '%'];
        }        
        if ($mobile) {
            $whe[] = ['mobile', '=', $mobile];
        }
        if ($addtime) {
            $time = explode(' - ', $addtime);
            $start_time = strtotime($time[0]);
            $end_time = strtotime($time[1]) - 1;
            if ($start_time > $end_time) {
                $this->err('开始时间不能大于结束时间');
            }
            $whe[] = ['addtime', 'BETWEEN', array($start_time, $end_time)];
        }
        if(!empty($last_login_ip)){
            $last_login_ip  = ip2long($last_login_ip);
            $user_id_arr = UserAccount::where(['last_login_ip'=>$last_login_ip])->column('user_id');
             
            if($user_id_arr){
              
                $whe[] = ['id', 'in', $user_id_arr];
            }else{
                $whe[] = ['id', '=', 0];
            }
        }
        $field = '*';
        $order = 'id desc';
        $data = UserModel::getList($whe, $field, $order, $this->page);
        foreach ($data['list'] as &$value) {
            $pid_info = UserModel::field('id,nickname,headimg')->where(['id' => $value['pid']])->find();
            $value['pid_info'] = $pid_info;
            #关联user_account
            $user_account =UserAccount::where(['user_id'=>$value['id']])->field('last_login_ip1,last_login_ip,ip_adcode,ip_province,ip_city')->find();
           
            $last_login_ip = 0;
            if($user_account){
               if($user_account['last_login_ip']){
                    if($user_account['last_login_ip1']){
                        $last_login_ip = $user_account['last_login_ip1'];
                    }else{
                        $last_login_ip = long2ip($user_account['last_login_ip']);
                    }
                   
               }
              
            }
            $value['last_login_ip']  = $last_login_ip;
            $value['ip_adcode'] = $user_account['ip_adcode'];
            $value['ip_province'] = $user_account['ip_province'];
            $value['ip_city'] = $user_account['ip_city'];
        }
        View::assign('list', $data['list']);
        View::assign('user_id', $user_id);
        View::assign('mobile', $mobile);
        View::assign('nickname', $nickname);
        View::assign('addtime', $addtime);
        View::assign('last_login_ip', $last_login_ip2);


        View::assign('count', $data['count']);
        View::assign('page', $data['page']);
        return View::fetch('User/index');
    }
    
    /**
     * 用户仓库信息
     */ 
    public function pata_list(Request $request)
    {
        $user_id = request()->param('id', '');
        $uids = explode('.', $user_id);
        if (is_array($uids) and count($uids) > 1) {
            $user_id = $uids[0];
        }
        $keyword = trim(input('get.keyword', ' ', 'htmlentities'));

        $where = [];
        // $where[] = ['status', '=', 1];
        $where[] = ['type', '=', 11];
        if (!empty($keyword)) {
            $where[] = ['title', 'like', '%' . $keyword . '%'];
        }
        $field = '*';
        $order = 'id desc';
        $list = Goods::where($where)->field($field)->order($order)->paginate(['list_rows' => 20, 'query' => request()->param()]);
        $page = $list->render();
        $total_num = 0;
        $data['list'] = $list->toArray()['data'];
        foreach ($data['list'] as $k => &$v) {
            $w = [];
            $w[] = ['goods_id', '=', $v['id']];
            $w[] = ['user_id', '=', $user_id];
            $v['number'] = ClimbRank::where($w)->field('id')->count('id');
            $total_num+=$v['number'];
        }
        $data['last_page'] = $list->toArray()['last_page'];
        $data['count'] = $list->total();
        $data['page'] = $page;
        View::assign('list', $data['list'] );
        View::assign('count', $data['count']);
        View::assign('user_id', $user_id);
        View::assign('keyword', $keyword);
        View::assign('total_num', $total_num);
        View::assign('page', $data['page']);
        return View::fetch("User/pata_list");
    }
    
    
        /**
     * 用户仓库信息
     */ 
    public function order_list(Request $request)
    {
        $user_id = request()->param('id', '');
        $uids = explode('.', $user_id);
        if (is_array($uids) and count($uids) > 1) {
            $user_id = $uids[0];
        }
        $order_type = trim(input('get.order_type'));// 1一番赏 2无限赏 3擂台赏 4抽卡机 5积分赏 6全局赏 7福利盲盒  8领主赏  9连击赏 10权益领取
        $keyword = trim(input('get.keyword', ' ', 'htmlentities'));
        $insurance_is = trim(input('get.insurance_is')); //   是否保险柜 保险柜0否 1是',
        $goodslist_type = trim(input('get.goodslist_type')); // '1现货 2预售'

        $where = [];
        $where[] = ['user_id', '=', $user_id];
        $where[] = ['status', '=', 0];
        // if (!empty($goodslist_type)) {
        //     $where[] = ['goodslist_type', '=', $goodslist_type];
        // } else {
        //     $where[] = ['goodslist_type', '=',2];
        // }
        // if (!empty($keyword)) {
        //     $where[] = ['goodslist_title', 'like', '%' . $keyword . '%'];
        // }
        // if (!empty($order_type)) {
        //     $where[] = ['order_type', '=', $order_type];
        // } 
        $field = 'goodslist_type, goodslist_id, user_id, count(id) as prize_num, id, shang_id, goodslist_imgurl, sum(goodslist_money)  goodslist_money, goodslist_price, goodslist_title, order_type, addtime';
        $order = 'id desc';
        $list = OrderList::where($where)->group("goodslist_id")->field($field)->order($order)->paginate(['list_rows' => 20, 'query' => request()->param()]);
        $page = $list->render();
        $total_money = 0;
        $data['list'] = $list->toArray()['data'];
        foreach ($data['list'] as $k => &$v) {
            $v['shang_title'] = Shang::where(['id'=> $v['shang_id']])->value('title');
            $total_money += $v['goodslist_money'];
        }
        $data['last_page'] = $list->toArray()['last_page'];
        $data['count'] = $list->total();
        $data['page'] = $page;
        View::assign('list', $data['list'] );
        View::assign('count', $data['count']);
        View::assign('user_id', $user_id);
        View::assign('page', $data['page']);
        View::assign('total_money', $total_money);
        return View::fetch("User/order_list");
    }
    /**
     * 资金变动
     */
    public function chongzhi()
    {
        $id = request()->param('id', '');
        $type = request()->param('type', '');
        $user_info = UserModel::find($id);
        if (!$user_info) {
            $this->renderError('请求参数错误');
        }
        if (\request()->IsGet()) {
            if ($type == 1) {
                $money = $user_info['money'];
            } elseif ($type == 2) {
                $money = $user_info['ou_qi'];
            } elseif ($type == 3) {
                $money = $user_info['score'];
            } else {
                $this->renderError('请求参数错误1');
            }
            View::assign('id', $id);
            View::assign('type', $type);
            View::assign('money', $money);
            return View::fetch('User/chongzhi');
        } else {
            $money = request()->param('money', '');
            $type_is = request()->param('type_is', '');
            if ($type_is != 1 && $type_is != 2) {
                $this->renderError('请求参数错误1');
            }
            if (empty($money)) {
                return $this->renderError('请输入修改数量');
            }
            Db::startTrans();
            if ($type == 1) {#余额
                if (RegMoney($money)) {
                    return $this->renderError('修改数量不规范,最多保留两位小数');
                }
                if ($type_is == 2) {
                    if ($money > $user_info['money']) {
                        return $this->renderError('账号余额扣除数量不足');
                    }
                    $money = $money * -1;
                }
                $res[] = UserModel::changeMoney($id, $money, 1, '后台变动');
            } elseif ($type == 2) {#欧气
                if (RegInt($money)) {
                    return $this->renderError('修改数量不规范,请输入大于0的整数');
                }
                if ($type_is == 2) {
                    if ($money > $user_info['integral']) {
                        return $this->renderError('账号潮币扣除数量不足');
                    }
                    $money = $money * -1;
                }
                $res[] = UserModel::changeOuQi($id, $money, 5, '后台变动');
                
                $ss = UserModel::ou_qi_level_up($id, $money, 2);
                $res = array_merge($ss, $res);
            } elseif ($type == 3) {#积分
                if (RegInt($money)) {
                    return $this->renderError('修改数量不规范,请输入大于0的整数');
                }
                if ($type_is == 2) {
                    if ($money > $user_info['score']) {
                        return $this->renderError('账号积分扣除数量不足');
                    }
                    $money = $money * -1;
                }
                $res[] = UserModel::changeScore($id, $money, 1, '后台变动');
            } else {
                $this->renderError('请求参数错误2');
            }
            if (resCheck($res)) {
                Db::commit();
                return $this->renderSuccess("操作成功");
            } else {
                Db::rollback();
                return $this->renderError("操作失败");
            }
        }


    }

    /**
     * 封号、解封处理
     */
    public function userdel(Request $request)
    {
        $id = request()->post('id/d', 0);
        $type = request()->post('type/d', 0);
        if ($type != 1 && $type != 2) {
            return $this->renderError('请求参数错误');
        }
        $user = UserModel::getInfo(['id' => $id]);
        if (!$user) {
            return $this->err('数据不存在');
        }
        $result = $user->save(["status" => $type]);
        if ($result) {
            return $this->renderSuccess('操作成功');
        } else {
            return $this->renderError('操作失败');
        }
    }
    
    /*
        ip转换
    */
     public function ipzh(Request $request)
    {
      
        $id = request()->post('id/d', 0);
        $user_account = UserAccount::where(['user_id'=>$id])->field('last_login_ip1,ip_province,last_login_ip')->find();
        if($user_account){
            if(empty($user_account['ip_province'])){
                $last_login_ip = long2ip($user_account['last_login_ip']);
                //$last_login_ip = $user_account['last_login_ip1'];
                var_dump($last_login_ip);
                $url = "https://restapi.amap.com/v3/ip?key=6a46ad822120e393956e89d498e8c40b&ip="."$last_login_ip"."";
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                
                $result = curl_exec($ch);
                curl_close($ch);
                
                $result = json_decode($result, true);
                var_dump($result);
                exit;
                if( $result['status'] == '1'){
                    
                   $res = UserAccount::where(['user_id'=>$id])->update([
                        'ip_adcode'=>$result['adcode'],
                        'ip_province'=>$result['province'],
                        'ip_city'=>$result['city']
                        ]);
                }else{
                    $res = false;
                }
            }
            
        }else{
             $res = false;
        }
        if ($res) {
            return $this->renderSuccess('操作成功');
        } else {
            return $this->renderError('操作失败');
        }
    }

    /**
     * 赠送卡牌查找
     */
    public function give_goodslist_info()
    {
        $card_no = request()->param('card_no', '');
        $goodslist = GoodsList::where('card_no', '=', $card_no)
            ->find();
        if (!$goodslist) {
            return $this->renderError('输入错误,未找到奖品信息');
        }
        #验证是否赠送是卡册盒子
        $good_info = Goods::field('id,type')->where('id', '=', $goodslist['goods_id'])->find();
        if ($good_info['type'] != 4) {
            return $this->renderError('只可赠送卡册盒子');
        }        
        $data = [
            'title' => $goodslist['title'],
            'imgurl' => imageUrl($goodslist['imgurl']),
        ];
        return $this->renderSuccess('查找成功', $data);
    }

    /**
     * 赠送卡牌
     */
    public function give_goodslist()
    {
        $user_id = request()->param('id/d', 0);
        $user_info = UserModel::find($user_id);
        if (!$user_info) {
            $this->renderError('请求参数错误');
        }
        if (request()->IsGet()) {
            View::assign('id', $user_id);
            return View::fetch('User/give_goodslist');
        } else {
            $card_no = request()->param('card_no', '');
            $num = request()->param('num/d', 0);
            $goodslist = GoodsList::where('card_no', '=', $card_no)
                ->find();
            if (!$goodslist) {
                return $this->renderError('输入错误,未找到奖品信息');
            }
            if (RegInt($num)) {
                return $this->renderError('数量输入错误,请输入大于0的整数');
            }
            #验证是否赠送是卡册盒子
            $good_info = Goods::field('id,type')->where('id', '=', $goodslist['goods_id'])->find();
            if ($good_info['type'] != 4) {
                return $this->renderError('只可赠送卡册盒子');
            }            
            $save_prize = [
                'order_id' => 0,
                'user_id' => $user_id,
                'status' => 0,#0未操作 1选择兑换 2选择发货
                'goods_id' => $goodslist['goods_id'],
                'num' => 0,
                'shang_id' => $goodslist['shang_id'],
                'goodslist_id' => $goodslist['id'],
                'goodslist_title' => $goodslist['title'],
                'goodslist_imgurl' => $goodslist['imgurl'],
                'goodslist_price' => $goodslist['price'],
                'goodslist_money' => $goodslist['money'],
                'goodslist_type' => $goodslist['goods_type'],
                'goodslist_sale_time' => $goodslist['sale_time'],
                'addtime' => time(),
                'prize_code' => $goodslist['prize_code'],
                'order_type' => 9,
            ];
            $all_save_prize = [];
            for ($i = 0; $i < $num; $i++) {
                $all_save_prize[] = $save_prize;
            }
            $res = OrderList::insertAll($all_save_prize);
            if ($res) {
                return $this->renderSuccess("操作成功");
            } else {
                return $this->renderError("操作失败");
            }
        }


    }


    /**
     * 增减仓库数量
     */
    public function give_order_list(Request $request){
        if(!$request->isPost()){
            $goodslist_id = $request->param("goodslist_id");
            $type = $request->param("type");
            View::assign("goodslist_id",$goodslist_id);
            View::assign("type",$type);
            return View::fetch("User/give_order_list");
        }else{
            $data = input('post.');
            if(empty($data['num'])){
                return $this->renderError("请输入数量");
            }
            if ($data['num'] < 1) {
                return $this->renderError("数量输入有误");
            }
            $num = $data['num'];
            $order_list = OrderList::where(['id' => $data['goodslist_id']])->order('id asc')->find();
            
            $time = time();
            if ($data['type'] == '1') {
                $add = [];
                for($k=0; $k<$num; $k++) {
                    $add[$k]['order_id'] = $order_list['order_id'];
                    $add[$k]['user_id'] = $order_list['user_id'];
                    $add[$k]['recovery_num'] = $order_list['recovery_num'];
                    $add[$k]['send_num'] = $order_list['send_num'];
                    $add[$k]['status'] = $order_list['status'];
                    $add[$k]['goods_id'] = $order_list['goods_id'];
                    $add[$k]['num'] = $order_list['num'];
                    $add[$k]['shang_id'] = $order_list['shang_id'];
                    $add[$k]['goodslist_id'] = $order_list['goodslist_id'];
                    $add[$k]['goodslist_title'] = $order_list['goodslist_title'];
                    $add[$k]['goodslist_imgurl'] = $order_list['goodslist_imgurl'];
                    $add[$k]['goodslist_price'] = $order_list['goodslist_price'];
                    $add[$k]['goodslist_money'] = $order_list['goodslist_money'];
                    $add[$k]['goodslist_type'] = $order_list['goodslist_type'];
                    $add[$k]['goodslist_sale_time'] = $order_list['goodslist_sale_time'];
                    $add[$k]['choice_time'] = $order_list['choice_time'];
                    $add[$k]['insurance_is'] = $order_list['insurance_is'];
                    $add[$k]['order_type'] = $order_list['order_type'];
                    $add[$k]['order_list_id'] = $order_list['order_list_id'];
                    $add[$k]['luck_no'] = $order_list['luck_no'];
                    $add[$k]['prize_code'] = $order_list['prize_code'];
                    $add[$k]['is_chong'] = $order_list['is_chong'];
                    $add[$k]['source'] = $order_list['source'];
                    $add[$k]['order_type'] = $order_list['order_type'];
                    $add[$k]['addtime'] = $time + $k;
                }
                $dd = Db::name('order_list')->insertAll($add);
            } else {
               $ww = [];
               $ww[] = ['goodslist_id', '=', $order_list['goodslist_id']];
               $ww[] = ['user_id', '=', $order_list['user_id']];
               $count =  OrderList::where($ww)->count();
               if ($count < $num) {
                    return $this->renderError("盒柜赏品数量不足");
               }
               $dd  = OrderList::where($ww)->limit($num)->delete();
            }
            if($dd){
                return $this->renderSuccess("操作成功");
            }else{
                return $this->renderError("操作失败");
            }
        }
    }
    /**
     * 赠送
     */
    public function give_add(Request $request){
        if(!$request->isPost()){
            $w = [];
            $w[] = ['status','=',0];
            $coupon = Coupon::getAllList($w,'id,title,price,man_price,ttype');
            View::assign('coupon',$coupon);

            $user_id = $request->param("user_id");
            View::assign("user_id",$user_id);
            return View::fetch("User/give_add");
        }else{
            $data = input('post.');
            if(empty($data['give_id'])){
                return $this->renderError("请选择赠送的物品");
            }
            $coupon = Coupon::getInfo(['id' => $data['give_id']]);
            if (!$coupon || $coupon['status'] != 0){
                return $this->renderError("优惠券不存在或者已下架");
            }

            //赠送优惠卷
            $data2 = [];
            for($i=0;$i<$data['num'];$i++){
                $data2[$i]['title'] = $coupon['title'];
                $data2[$i]['price'] = $coupon['price'];
                $data2[$i]['man_price'] = $coupon['man_price'];
                $data2[$i]['end_time'] =  $coupon['effective_day'] * 86400 + time();
                $data2[$i]['addtime'] = time();
                $data2[$i]['status'] = 0;
                $data2[$i]['user_id'] = $data['user_id'];
                $data2[$i]['coupon_id'] = $data['give_id'];
                $data2[$i]['state'] = $coupon['ttype'];
            }
            $dd = Db::name('coupon_receive')->insertAll($data2);
            if($dd){
                return $this->renderSuccess("赠送成功");
            }else{
                return $this->renderError("赠送失败");
            }
        }
    }

    /**
     * 用户盈亏
     */
    public function user_profit_loss()
    {
        $whe = [];
        $where = [];
        $addtime = trim(input('get.addtime'));
        $uid = trim(input('get.uid'));
        if (!empty($uid)) {
            $whe[] = ['id', '=', $uid];
        }
        if (!empty($addtime)) {
            $addtime = explode(' - ', $addtime);
            $start_time = strtotime($addtime[0]);
            $end_time = strtotime($addtime[1]) - 1;
            $where[] = ['addtime', 'BETWEEN', [$start_time, $end_time]];
        } 
        // else {
        //     $start_time = strtotime(date('Y-m-d', time()));
        //     $end_time = $start_time + 86399;
        //     $where[] = ['addtime', 'BETWEEN', [$start_time, $end_time]];
        // }
        $data = UserModel::getList($whe, 'id,nickname,headimg,money', 'id desc', 20);
        $cz_money_total = 0;
        $wx_money_total = 0;
        $cz_yue_total = 0;
        $cz_integral_total = 0;
        $price_total =0;
        $shang_money_total = 0;
        $fh_money_total = 0;
        $tx_money_total = 0;
        $profit_loss_total = 0;
        $money = 0;
        foreach ($data['list'] as $k => &$v) {
            #公式 (充值余额 + 潮币 + 微信支付 - 余额 - 背包赏品
            $cz_money = ProfitMoney::field('change_money')->where('user_id', '=', $v['id'])->where('type', '=', 1)->where('change_money', '>', 0)->where($where)->sum('change_money');
            $wx_money = ProfitMoney::field('change_money')->where('user_id', '=', $v['id'])->where('type', '=', 2)->where('change_money', '>', 0)->where($where)->sum('change_money');
            $cz_yue = $cz_money + $wx_money;
            $cz_integral = ProfitIntegral::field('change_money')->where('user_id', '=', $v['id'])->where('type', '=', 1)->where('change_money', '>', 0)->where($where)->sum('change_money');
            $price = Order::field('price')->where('user_id', '=', $v['id'])->where('status', '=', 1)->where('price', '>', 0)->where($where)->sum('price');
            $shang_money = OrderList::field('goodslist_money')->where('user_id', '=', $v['id'])->whereIn('status',[0])->where('goodslist_money', '>', 0)->where($where)->sum('goodslist_money');
            $fh_money = OrderList::field('goodslist_money')->where('user_id', '=', $v['id'])->where('status', '=', 2)->where('goodslist_money', '>', 0)->where($where)->sum('goodslist_money');
            $tx_money = ProfitMoney2::field('change_money')->where('user_id', '=', $v['id'])->where('type', '=', 5)->where('change_money', '<', 0)->where($where)->sum('change_money');
            $profit_loss = $cz_yue  + $price - $v['money'] - $shang_money - $fh_money;
            $profit_loss = $profit_loss + $tx_money;
            $v['cz_money'] = $cz_yue;
            $v['wx_money'] = $wx_money;
            $v['cz_integral'] = $cz_integral;
            $v['price'] = $price;
            $v['shang_money'] = $shang_money;
            $v['fh_money'] = $fh_money;
            $v['tx_money'] = $tx_money;
            $v['profit_loss'] = $profit_loss;
            
            
            $cz_money_total+=$cz_yue;
            $wx_money_total+=$wx_money;
            $cz_yue_total+=$cz_yue;
            $cz_integral_total+=$cz_integral;
            $price_total+= $price;
            $shang_money_total += $shang_money;
            $fh_money_total += $fh_money;
            $tx_money_total += $tx_money;
            $profit_loss_total += $profit_loss;
            $money += $v['money'];
            
        }
         $total_money[1]['cz_money_total'] = $cz_money_total;
        $total_money[1]['cz_integral_total'] = $cz_integral_total;
//        $total_money[1]['wx_money_total'] = $wx_money_total;
        $total_money[1]['price_total'] = $price_total;
        $total_money[1]['total_money'] = $money;

//        $total_money[1]['cz_yue_total'] = $cz_yue_total;


        $total_money[1]['shang_money_total'] = $shang_money_total;
        $total_money[1]['fh_money_total'] = $fh_money_total;
        $total_money[1]['tx_money_total'] = $tx_money_total;
        $total_money[1]['profit_loss_total'] = $profit_loss_total;
        View::assign('list', $data['list']);
        View::assign('count', $data['count']);
        View::assign('page', $data['page']);
        View::assign('total_money', $total_money);
        
        View::assign('addtime', $addtime);
        View::assign('uid', $uid);
        return View::fetch("User/user_profit_loss");
        
    }


    /**
     * vip管理
     */
    public function vip()
    {
        $list = UserVip::order('id asc')->select();
        View::assign('list', $list);
        View::assign('count', count($list));
        return View::fetch("User/vip");
    }


    /**
     * vip编辑
     */
    public function vip_edit(Request $request)
    {
        if (!$request->isPost()) {
            $id = request()->param('id/d', 0);
            $info = UserVip::where(['id' => $id])->find();
            if (!$info) {
                return $this->renderError('请求参数错误');
            }
            View::assign('info', $info);
            return View::fetch('User/vip_edit');
        } else {
            $data = input('post.');
            if (empty($data['id'])) {
                return $this->renderError('请求参数错误');
            }
            $info = UserVip::where(['id' => $data['id']])->find();
            if (!$info) {
                return $this->renderError('请求参数错误1');
            }
            if (empty($data['title'])) {
                return $this->renderError('请输入vip名称');
            }
            if (RegZero($data['condition'])) {
                return $this->renderError('升级消费设置错误,请设置整数');
            }
            if (RegMoney($data['discount'])) {
                return $this->renderError('vip折扣设置错误,最多保留两位小数');
            }
//            if (empty($data['imgurl'])) {
//                return $this->renderError('请上传图标');
//            }
            $data['update_time'] = time();
            unset($data['id']);
            $dd = $info->allowField([])->save($data);
            if ($dd) {
                return $this->renderSuccess('编辑成功');
            } else {
                return $this->renderError('编辑失败');
            }
        }
    }

    /**
     * 流水明细
     *created by Admin at 2023/2/10 14:23
     */
    public function detailed_flow(){
        $whe = [];
        $where = [];
//        $addtime = trim(input('get.addtime'));
        $uid = trim(input('get.uid'));
        if (!empty($uid)) {
            $whe[] = ['user_id', '=', $uid];
        }
//        if (!empty($addtime)) {
//            $addtime = explode(' - ', $addtime);
//            $start_time = strtotime($addtime[0]);
//            $end_time = strtotime($addtime[1]) - 1;
//            $where[] = ['addtime', 'BETWEEN', [$start_time, $end_time]];
//        } else {
//            $start_time = strtotime(date('Y-m-d', time()));
//            $end_time = $start_time + 86399;
//            $where[] = ['addtime', 'BETWEEN', [$start_time, $end_time]];
//        }

//        $data = ProfitMoney::getList($whe, 'id,user_id,change_money,addtime', '', 20);
        $list = ProfitMoney::field('user_id,sum(change_money) as new_money')
//            ->whereIn('type',[])
            ->group('user_id')
            ->order('new_money desc')
            ->paginate(20);
        $page = $list->render();
        $data['list'] = $list->toArray()['data'];
        $data['count'] = $list->total();
        $data['page'] = $page;
        $num = 1;
        foreach ($data['list'] as &$value){
//            dd($value['user_id']);
            $user = \app\common\model\User::where('id',$value['user_id'])->find();
            $value['nick_name'] = $user['nickname'];
            $value['headimg'] = $user['headimg'];
            $value['openid'] = $user['openid'];
            $value['num'] =$num;
//            $value['addtime'] =$user['addtime'];
            $num++;
        }
//        dd($data);
        View::assign('list', $data['list']);
        View::assign('count', $data['count']);
        View::assign('page', $data['page']);
        return View::fetch("User/detailed_flow");
    }

    /**
     * 下级用户
     *created by Admin at 2023/2/16 15:55
     */
    public function user_team(Request $request){
        $id = $request->param('id');
//        dd($id);
        $list = \app\common\model\User::where('pid',$id)->paginate(20);
        $page = $list->render();
        $data['list'] = $list->toArray()['data'];
        $data['count'] = $list->total();
        $data['page'] = $page;
        foreach ($data['list'] as &$value){
            $value['total'] = ProfitMoney::where('type',5)
                ->where('user_id',$id)
                ->where('share_uid',$value['id'])
                ->sum('change_money');
//            dd();
        }
//        dd($data['list']);
        View::assign('list', $data['list']);
        View::assign('count', $data['count']);
        View::assign('page', $data['page']);
        return View::fetch("User/user_team");
    }
    
    public function ip_list(Request $request){
        $id = $request->param('id');
//        dd($id);
        $list = UserLoginIp::where('user_id',$id)->order('id desc')->paginate(20);
        $page = $list->render();
        $data['list'] = $list->toArray()['data'];
        $data['count'] = $list->total();
        $data['page'] = $page;
        View::assign('list', $data['list']);
        View::assign('count', $data['count']);
        View::assign('page', $data['page']);
        return View::fetch("User/ip_list");
    }
    
    
    /**
     * 添加奖品
     */
    public function goodslist_add(Request $request)
    {
        if (!$request->isPost()) {
            $user_id = $request->param('user_id');
            View::assign('user_id', $user_id);
            return View::fetch('User/goodslist_add');
        } else {
            $data = input('post.');
            if (RegMoney($data['money'])) {  
                return $this->renderError('兑换价格设置错误,最多保留两位小数');
            }
            $save_sports_data = [];
            if (empty($data['title'])) {
                return $this->renderError('请填写图片标题');
            }
            $data['card_no'] = NULL;
            if (empty($data['imgurl'])) {
                return $this->renderError('请上传图片');
            }
            $data['addtime'] = time();
            $data['goods_id'] = '-6';
            
            Db::startTrans();
            $goodslist_id = GoodsList::insertGetId($data);
            $save_order_list = [
                'order_id' => 0,
                'user_id' => $data['user_id'],
                'status' => 0,#0未操作 1选择兑换 2选择发货
                'goods_id' => '-6',  //用户专有
                'num' => 0,
                'shang_id' => 0,
                'goodslist_id' => $goodslist_id,
                'goodslist_title' => $data['title'],
                'goodslist_imgurl' => $data['imgurl'],
                'goodslist_price' => $data['price'],
                'goodslist_money' => $data['money'],
                'goodslist_type' => 1,
                'addtime' => time(),
                'prize_code' => getPrizeCode() . '_' . time(),
                'order_type' => 0,
            ];
            $ss = OrderList::insert($save_order_list);
            
            if ($goodslist_id && $ss) {
                Db::commit();
                return $this->renderSuccess('添加成功');
            } else {
                Db::rollback();
                return $this->renderError('添加失败');
            }
        }
    }
    
    
     /**
     * 用户信息导出
     */
    public function user_info_daochu(Request $request)
    {
        $user_id = trim(input('get.user_id'));
        $mobile = trim(input('get.mobile'));
        $nickname = trim(input('get.nickname'));
        // $addtime = trim(input('get.addtime'));
        $addtime = $request->param('addtime');

        $last_login_ip = trim(input('get.last_login_ip'));
        $whe = [];
        if ($user_id) {
            $whe[] = ['id', '=', $user_id];
        }
        if ($nickname) {
            $whe[] = ['nickname', 'like', '%' . $nickname . '%'];
        }        
        if ($mobile) {
            $whe[] = ['mobile', '=', $mobile];
        }
        if ($addtime) {
            // $time = explode(' - ', $addtime);
            $start_time = strtotime($time[0]);
            $end_time = strtotime($time[1]) - 1;
            if ($start_time > $end_time) {
                $this->err('开始时间不能大于结束时间');
            }
            $whe[] = ['addtime', 'BETWEEN', array($start_time, $end_time)];
        }
        if(!empty($last_login_ip)){
            $last_login_ip  = ip2long($last_login_ip);
            $user_id_arr = UserAccount::where(['last_login_ip'=>$last_login_ip])->column('user_id');
             
            if($user_id_arr){
              
                $whe[] = ['id', 'in', $user_id_arr];
            }else{
                $whe[] = ['id', '=', 0];
            }
        }
        $field = '*';
        $order = 'id desc';
        $data = UserModel::where($whe)->order('id desc')->select()->toArray();

        foreach ($data as &$value) {
            $pid_info = UserModel::field('id,nickname,headimg')->where(['id' => $value['pid']])->find();
            $value['pid_info'] = $pid_info;
            #关联user_account
            $user_account =UserAccount::where(['user_id'=>$value['id']])->field('last_login_ip1,last_login_ip,ip_adcode,ip_province,ip_city')->find();
           
            $last_login_ip = 0;
            if($user_account){
              if($user_account['last_login_ip']){
                    if($user_account['last_login_ip1']){
                        $last_login_ip = $user_account['last_login_ip1'];
                    }else{
                        $last_login_ip = long2ip($user_account['last_login_ip']);
                    }
                   
              }
              
            }
            $value['last_login_ip']  = $last_login_ip;
            $value['ip_adcode'] = $user_account['ip_adcode'];
            $value['ip_province'] = $user_account['ip_province'];
            $value['ip_city'] = $user_account['ip_city'];
        }
        
        if (!$data) {
            return $this->renderError('未找到数据');
        }

        $save_name = substr(dirname($_SERVER['SCRIPT_FILENAME']), 0, -6);
        require $save_name . 'extend/phpexcel/PHPExcel.php';
        //3.实例化PHPExcel类
        $objPHPExcel = new \PHPExcel();
        //4.激活当前的sheet表
        $objPHPExcel->setActiveSheetIndex(0);
        //5.设置表格头（即excel表格的第一行）
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '用户信息')
            ->setCellValue('B1', '推荐人')
            ->setCellValue('C1', '余额')
            ->setCellValue('D1', '欧气')
            ->setCellValue('E1', '积分')
            ->setCellValue('F1', '状态')
            ->setCellValue('G1', '时间')
            ->setCellValue('H1', 'IP')
            ->setCellValue('I1', 'IP地址')
            ->setCellValue('J1', 'IP邮编');
        //设置A列水平居中
        $objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(25);

        $objPHPExcel->getActiveSheet()->getStyle('A')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
        $objPHPExcel->getActiveSheet()->getStyle('B')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
        $objPHPExcel->getActiveSheet()->getStyle('C')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
        $objPHPExcel->getActiveSheet()->getStyle('D')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
        $objPHPExcel->getActiveSheet()->getStyle('E')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
        $objPHPExcel->getActiveSheet()->getStyle('F')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
        $objPHPExcel->getActiveSheet()->getStyle('G')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
        $objPHPExcel->getActiveSheet()->getStyle('H')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
        $objPHPExcel->getActiveSheet()->getStyle('I')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
        $objPHPExcel->getActiveSheet()->getStyle('J')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);

        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A1:M1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A1:M1')->getAlignment()
            ->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);//垂直居中
        $objPHPExcel->getActiveSheet()->getStyle('A1:M1')->getFont()->setBold(true);

        //设置单元格宽度
        //6.循环刚取出来的数组，将数据逐一添加到excel表格。
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('A')->setWidth(40);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('B')->setWidth(50);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('C')->setWidth(30);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('D')->setWidth(30);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('E')->setWidth(30);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('F')->setWidth(30);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('G')->setWidth(50);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('H')->setWidth(30);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('I')->setWidth(30);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('J')->setWidth(30);


        $line = 1;
        foreach ($data as $key => &$value) {
            #订单号
            #用户信息
            $user_info = 'ID：' . $value['id'] . "     " . '昵称：' . $value['nickname'] . "     " . '手机号：' . $value['mobile'];
             $pid_info = '';
            if (!empty($value['pid_info'])) {
                $pid_info = 'ID：' . $value['pid_info']['id'] . "     " . '昵称：' . $value['pid_info']['nickname'];
            }
        
            #状态
            $status = '正常';
            if ($value['status'] == '2') {
                $status = '禁用';
            }
    
            #申请时间
            $addtime = date('Y-m-d H:i:s', $value['addtime']);

            $line++;
        
            #开始导出
            $objPHPExcel->getActiveSheet()->setCellValue('A' . $line, $user_info);#用户信息
            $objPHPExcel->getActiveSheet()->setCellValue('B' . $line, $pid_info);#上级用户
            $objPHPExcel->getActiveSheet()->setCellValue('C' . $line, $value['money']);#余额
            $objPHPExcel->getActiveSheet()->setCellValue('D' . $line, $value['ou_qi']);#欧气
            $objPHPExcel->getActiveSheet()->setCellValue('E' . $line, $value['score']);#积分
            $objPHPExcel->getActiveSheet()->setCellValue('F' . $line, $status);#状态
            $objPHPExcel->getActiveSheet()->setCellValue('G' . $line, $addtime);#时间
            $objPHPExcel->getActiveSheet()->setCellValue('H' . $line, $value['last_login_ip']);#登录IP
            $objPHPExcel->getActiveSheet()->setCellValue('I' . $line, $value['ip_province'] . $value['ip_city']);#IP地址
            $objPHPExcel->getActiveSheet()->setCellValue('J' . $line, $value['ip_adcode'] );#Ip邮箱
        }
        //7.设置保存的Excel表格名称
        $filename = '用户列表信息' . date('y-m-d H_i_s', time()) . '.xls';
        //8.设置当前激活的sheet表格名称；
        $objPHPExcel->getActiveSheet()->setTitle('用户信息');
        //9.设置浏览器窗口下载表格
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="' . $filename . '"');
        //生成excel文件
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        //下载文件在浏览器窗口
        $objWriter->save('php://output');
        exit;
    }
    
    //盈亏导出
    public function  user_profit_loss_daochu(Request $request)
    {        
        $whe = [];
        $where = [];
        // $addtime = trim(input('get.addtime'));
        $addtime = $request->param('addtime');
        $uid = trim(input('get.uid'));
        if (!empty($uid)) {
            $whe[] = ['id', '=', $uid];
        }
        if (!empty($addtime)) {
            // $addtime = explode(' - ', $addtime);
            $start_time = strtotime($addtime[0]);
            $end_time = strtotime($addtime[1]) - 1;
            $where[] = ['addtime', 'BETWEEN', [$start_time, $end_time]];
        } 

        $data = UserModel::where($whe)->field('id,nickname,headimg,money,mobile')->order('id desc')->select()->toArray();
        $cz_money_total = 0;
        $wx_money_total = 0;
        $cz_yue_total = 0;
        $cz_integral_total = 0;
        $price_total =0;
        $shang_money_total = 0;
        $fh_money_total = 0;
        $tx_money_total = 0;
        $profit_loss_total = 0;
        $money = 0;
        $total_money = [];
        foreach ($data as $k => &$v) {
            #公式 (充值余额 + 潮币 + 微信支付 - 余额 - 背包赏品
            $cz_money = ProfitMoney::field('change_money')->where('user_id', '=', $v['id'])->where('type', '=', 1)->where('change_money', '>', 0)->where($where)->sum('change_money');
            $wx_money = ProfitMoney::field('change_money')->where('user_id', '=', $v['id'])->where('type', '=', 2)->where('change_money', '>', 0)->where($where)->sum('change_money');
            $cz_yue = $cz_money + $wx_money;
            $cz_integral = ProfitIntegral::field('change_money')->where('user_id', '=', $v['id'])->where('type', '=', 1)->where('change_money', '>', 0)->where($where)->sum('change_money');
            $price = Order::field('price')->where('user_id', '=', $v['id'])->where('status', '=', 1)->where('price', '>', 0)->where($where)->sum('price');
            $shang_money = OrderList::field('goodslist_money')->where('user_id', '=', $v['id'])->whereIn('status',[0])->where('goodslist_money', '>', 0)->where($where)->sum('goodslist_money');
            $fh_money = OrderList::field('goodslist_money')->where('user_id', '=', $v['id'])->where('status', '=', 2)->where('goodslist_money', '>', 0)->where($where)->sum('goodslist_money');
            $tx_money = ProfitMoney2::field('change_money')->where('user_id', '=', $v['id'])->where('type', '=', 5)->where('change_money', '<', 0)->where($where)->sum('change_money');
            $profit_loss = $cz_yue  + $price - $v['money'] - $shang_money - $fh_money;
            $profit_loss = $profit_loss + $tx_money;
            $v['cz_money'] = $cz_yue;
            $v['wx_money'] = $wx_money;
            $v['cz_integral'] = $cz_integral;
            $v['price'] = $price;
            $v['shang_money'] = $shang_money;
            $v['fh_money'] = $fh_money;
            $v['tx_money'] = $tx_money;
            $v['profit_loss'] = $profit_loss;
            
            
            $cz_money_total+=$cz_yue;
            $wx_money_total+=$wx_money;
            $cz_yue_total+=$cz_yue;
            $cz_integral_total+=$cz_integral;
            $price_total+= $price;
            $shang_money_total += $shang_money;
            $fh_money_total += $fh_money;
            $tx_money_total += $tx_money;
            $profit_loss_total += $profit_loss;
            $money += $v['money'];
            
        }
        
        if (!$data) {
            return $this->renderError('未找到数据');
        }

        $save_name = substr(dirname($_SERVER['SCRIPT_FILENAME']), 0, -6);
        require $save_name . 'extend/phpexcel/PHPExcel.php';
        //3.实例化PHPExcel类
        $objPHPExcel = new \PHPExcel();
        //4.激活当前的sheet表
        $objPHPExcel->setActiveSheetIndex(0);
        //5.设置表格头（即excel表格的第一行）
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '用户信息')
            ->setCellValue('B1', '充值余额')
            ->setCellValue('C1', '微信支付')
            ->setCellValue('D1', '余额')
            ->setCellValue('E1', '背包赏品')
            ->setCellValue('F1', '发货赏品')
            ->setCellValue('G1', '提现')
            ->setCellValue('H1', '盈亏');
        //设置A列水平居中
        $objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(25);

        $objPHPExcel->getActiveSheet()->getStyle('A')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
        $objPHPExcel->getActiveSheet()->getStyle('B')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
        $objPHPExcel->getActiveSheet()->getStyle('C')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
        $objPHPExcel->getActiveSheet()->getStyle('D')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
        $objPHPExcel->getActiveSheet()->getStyle('E')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
        $objPHPExcel->getActiveSheet()->getStyle('F')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
        $objPHPExcel->getActiveSheet()->getStyle('G')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
        $objPHPExcel->getActiveSheet()->getStyle('H')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);

        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A1:M1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A1:M1')->getAlignment()
            ->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);//垂直居中
        $objPHPExcel->getActiveSheet()->getStyle('A1:M1')->getFont()->setBold(true);

        //设置单元格宽度
        //6.循环刚取出来的数组，将数据逐一添加到excel表格。
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('A')->setWidth(40);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('B')->setWidth(50);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('C')->setWidth(30);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('D')->setWidth(30);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('E')->setWidth(30);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('F')->setWidth(30);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('G')->setWidth(50);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('H')->setWidth(30);

        $line = 2;
        foreach ($data as $key => &$value) {
            if ($line == 2) {
                $objPHPExcel->getActiveSheet()->setCellValue('A' . $line,  '总计');#用户信息
                $objPHPExcel->getActiveSheet()->setCellValue('B' . $line,  $cz_money_total);#cz_money
                $objPHPExcel->getActiveSheet()->setCellValue('C' . $line,  $price_total);#微信支付
                $objPHPExcel->getActiveSheet()->setCellValue('D' . $line,  $money);#余额
                $objPHPExcel->getActiveSheet()->setCellValue('E' . $line,  $shang_money_total);#背包赏品
                $objPHPExcel->getActiveSheet()->setCellValue('F' . $line, $fh_money_total);#发货赏品
                $objPHPExcel->getActiveSheet()->setCellValue('G' . $line, $tx_money_total);#提现
                $objPHPExcel->getActiveSheet()->setCellValue('H' . $line, $profit_loss_total);#盈亏
            }
            #订单号
            #用户信息
            $user_info = 'ID：' . $value['id'] . "     " . '昵称：' . $value['nickname'] . "     " . '手机号：' . $value['mobile'];

            $line++;
        
            #开始导出
            $objPHPExcel->getActiveSheet()->setCellValue('A' . $line, $user_info);#用户信息
            $objPHPExcel->getActiveSheet()->setCellValue('B' . $line, $value['cz_money']);#cz_money
            $objPHPExcel->getActiveSheet()->setCellValue('C' . $line, $value['price']);#微信支付
            $objPHPExcel->getActiveSheet()->setCellValue('D' . $line, $value['money']);#余额
            $objPHPExcel->getActiveSheet()->setCellValue('E' . $line, $value['shang_money']);#背包赏品
            $objPHPExcel->getActiveSheet()->setCellValue('F' . $line, $value['fh_money']);#发货赏品
            $objPHPExcel->getActiveSheet()->setCellValue('G' . $line, $value['tx_money']);#提现
            $objPHPExcel->getActiveSheet()->setCellValue('H' . $line, $value['profit_loss']);#盈亏

        }
        //7.设置保存的Excel表格名称
        $filename = '用户盈亏信息' . date('y-m-d H_i_s', time()) . '.xls';
        //8.设置当前激活的sheet表格名称；
        $objPHPExcel->getActiveSheet()->setTitle('用户盈亏信息');
        //9.设置浏览器窗口下载表格
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="' . $filename . '"');
        //生成excel文件
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        //下载文件在浏览器窗口
        $objWriter->save('php://output');
        exit;
        
    }
    
}
